<script>
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'PlanTable',
  setup() {
    // 列定义
    const columns = ref([
      { title: '计划编号', key: 'planId', visible: true },
      { title: '计划名称', key: 'planName', visible: true },
      { title: '部门名称', key: 'departmentName', visible: true },
      { title: '考核周期', key: 'assessmentCycle', visible: true },
      { title: '开始时间', key: 'startDate', visible: true },
      { title: '结束时间', key: 'endDate', visible: true },
      { title: '状态', key: 'status', visible: true }
    ])

    // 受控可见列 keys
    const visibleKeys = ref(columns.value.filter(col => col.visible).map(col => col.key))

    // 计算可见列详细信息
    const visibleColumns = computed(() => {
      return columns.value.filter(col => visibleKeys.value.includes(col.key))
    })

    // 数据
    const allData = ref([])
    const loading = ref(false)
    const total = ref(0)
    const pageSize = 10
    const currentPage = ref(1)

    // 搜索文本
    const searchText = ref('')

    // 搜索过滤
    const filteredData = computed(() => {
      if (!searchText.value) return allData.value
      return allData.value.filter(plan =>
        Object.values(plan).some(val => String(val).includes(searchText.value))
      )
    })

    // 分页数据
    const pagedData = computed(() => {
      return filteredData.value
    })

    function onSearch() {
      currentPage.value = 1
    }

    function handlePageChange(page) {
      currentPage.value = page
      fetchPlanData()
    }

    // 弹窗控制
    const showColumnModal = ref(false)
    let columnBackup = []

    watch(showColumnModal, (val) => {
      if (val) {
        columnBackup = [...visibleKeys.value]
      }
    })

    function cancelColumnSetting() {
      visibleKeys.value = [...columnBackup]
      showColumnModal.value = false
    }

    function confirmColumnSetting() {
      showColumnModal.value = false
    }

    // 计划详情弹窗相关
    const showPlanModal = ref(false)
    const selectedPlan = ref(null)

    function handleRowClick(row) {
      selectedPlan.value = row
      showPlanModal.value = true
    }

    function closePlanModal() {
      showPlanModal.value = false
      selectedPlan.value = null
    }

    function formatDate(dateStr) {
      if (!dateStr) return ''
      const d = new Date(dateStr)
      return d.toLocaleDateString('zh-CN')
    }

    // 获取考核计划数据
    async function fetchPlanData() {
      loading.value = true
      try {
        const res = await axios.get('http://127.0.0.1:8080/admin/assessment/getPlan', {
          params: {
            pageNum: currentPage.value,
            pageSize: pageSize
          },
          headers: {
            token: localStorage.getItem("token")
          }
        })
        
        if (res.data.code === 200) {
          const planData = res.data.data
          allData.value = planData.list.map(plan => ({
            planId: plan.planId,
            planName: plan.planName,
            departmentName: plan.departmentName,
            assessmentCycle: plan.assessmentCycle,
            startDate: plan.startDate,
            endDate: plan.endDate,
            status: plan.status === 1 ? '进行中' : (plan.status === 0 ? '已完成' : '未开始')
          }))
          total.value = planData.total
        } else {
          console.error('获取考核计划失败:', res.data.message)
        }
      } catch (error) {
        console.error('请求失败:', error)
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      fetchPlanData()
    })

    return {
      columns,
      visibleKeys,
      visibleColumns,
      allData,
      searchText,
      filteredData,
      onSearch,
      pageSize,
      currentPage,
      pagedData,
      total,
      loading,
      handlePageChange,
      showColumnModal,
      cancelColumnSetting,
      confirmColumnSetting,
      showPlanModal,
      selectedPlan,
      handleRowClick,
      closePlanModal,
      formatDate,
      fetchPlanData
    }
  }
}
</script>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}
</style>
<template>
  <div class="p-6 bg-white min-h-screen">
    <!-- 工具栏 -->
    <div class="flex justify-between items-center mb-4">
      <el-button type="primary" plain icon="el-icon-setting" @click="showColumnModal = true">
        列设置
      </el-button>

      <el-input
        v-model="searchText"
        placeholder="搜索考核计划"
        prefix-icon="el-icon-search"
        clearable
        @input="onSearch"
        style="width: 320px"
      />
    </div>

    <!-- 表格 -->
    <el-table 
      :data="pagedData" 
      border 
      style="width: 100%"
      @row-click="handleRowClick"
      :row-class-name="'cursor-pointer hover:bg-gray-50'"
      v-loading="loading"
    >
      <el-table-column
        v-for="col in visibleColumns"
        :key="col.key"
        :prop="col.key"
        :label="col.title"
        :min-width="100"
      >
        <template #default="scope">
          <span v-if="col.key === 'status'">
            <el-tag
              v-if="scope.row.status === '进行中'"
              type="success"
              effect="plain"
            >进行中</el-tag>
            <el-tag
              v-else-if="scope.row.status === '已完成'"
              type="primary"
              effect="plain"
            >已完成</el-tag>
            <el-tag
              v-else
              type="info"
              effect="plain"
            >未开始</el-tag>
          </span>
          <span v-else-if="col.key === 'assessmentCycle'">
            <el-tag
              v-if="scope.row.assessmentCycle === '月度'"
              type="info"
              effect="plain"
            >月度</el-tag>
            <el-tag
              v-else-if="scope.row.assessmentCycle === '季度'"
              type="warning"
              effect="plain"
            >季度</el-tag>
            <el-tag
              v-else
              type="success"
              effect="plain"
            >年度</el-tag>
          </span>
          <span v-else-if="col.key === 'departmentName'">
            <el-tag type="primary" effect="plain">
              {{ scope.row.departmentName }}
            </el-tag>
          </span>
          <span v-else-if="col.key === 'startDate' || col.key === 'endDate'">
            {{ formatDate(scope.row[col.key]) }}
          </span>
          <span v-else>{{ scope.row[col.key] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-between items-center mt-4">
      <div class="text-sm text-gray-600">共 {{ total }} 条</div>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 列设置弹窗 -->
    <el-dialog v-model="showColumnModal" title="列设置" width="30%" :close-on-click-modal="false">
      <el-checkbox-group v-model="visibleKeys">
        <el-checkbox
          v-for="col in columns"
          :key="col.key"
          :label="col.key"
        >
          {{ col.title }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="cancelColumnSetting">取消</el-button>
        <el-button type="primary" @click="confirmColumnSetting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 计划详情弹窗 -->
    <el-dialog 
      v-model="showPlanModal" 
      title="考核计划详情" 
      width="60%" 
      :close-on-click-modal="false"
      @close="closePlanModal"
    >
      <div v-if="selectedPlan" class="space-y-6">
        <!-- 基本信息 -->
        <div>
          <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">基本信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">计划编号：</span>
              <span class="text-gray-900">{{ selectedPlan.planId }}</span>
            </div>
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">计划名称：</span>
              <span class="text-gray-900">{{ selectedPlan.planName }}</span>
            </div>
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">所属部门：</span>
              <span class="text-gray-900">{{ selectedPlan.departmentName }}</span>
            </div>
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">考核周期：</span>
              <span class="text-gray-900">{{ selectedPlan.assessmentCycle }}</span>
            </div>
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">计划状态：</span>
              <el-tag
                v-if="selectedPlan.status === '进行中'"
                type="success"
                effect="plain"
              >进行中</el-tag>
              <el-tag
                v-else-if="selectedPlan.status === '已完成'"
                type="primary"
                effect="plain"
              >已完成</el-tag>
              <el-tag
                v-else
                type="info"
                effect="plain"
              >未开始</el-tag>
            </div>
          </div>
        </div>

        <!-- 时间信息 -->
        <div>
          <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">时间信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">开始时间：</span>
              <span class="text-gray-900">{{ formatDate(selectedPlan.startDate) }}</span>
            </div>
            <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">结束时间：</span>
              <span class="text-gray-900">{{ formatDate(selectedPlan.endDate) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="flex justify-end space-x-3">
          <el-button @click="closePlanModal">关闭</el-button>
          <el-button type="primary" @click="closePlanModal">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

